package com.hjy.controller;

import com.hjy.dao.DepartmentDao;
import com.hjy.dao.EmployeeDao;
import com.hjy.pojo.Department;
import com.hjy.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class UserController {

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/user/login")
    public String login(String username, String password, Model model, HttpSession session){
        if ("admin".equals(username)&&"123456".equals(password)){
            session.setAttribute("username",username);
            return "redirect:/main.html";
        }
        model.addAttribute("message","用户名或者密码错误");
        return "index";
    }

    @RequestMapping("/emps")
    public String emps(Model model){
        Collection<Employee> daoAll = employeeDao.findAll();
        model.addAttribute("emps",daoAll);
        return "list";
    }

    @RequestMapping("emp")
    public String emp(Model model){
        Collection<Department> all = departmentDao.findAll();
        model.addAttribute("departments",all);
        return "add";
    }
    @RequestMapping("empAdd")
    public String empAdd(Model model,Employee employee){
        System.out.println("employee ====>"+employee);
        Integer id = employee.getDepartment().getId();
        employee.setDepartment(departmentDao.findById(id));
        employeeDao.insert(employee);
        return "redirect:/emps";
    }

    @RequestMapping("toUpdate")
    public String toUpdate(Integer id,Model model){
        Employee employee = employeeDao.findById(id);
        model.addAttribute("employee",employee);
        Collection<Department> all = departmentDao.findAll();
        model.addAttribute("departments",all);
        return "update";
    }

    @RequestMapping("update")
    public String update(Employee employee,Model model){
        Integer id = employee.getDepartment().getId();
        employee.setDepartment(departmentDao.findById(id));
        employeeDao.update(employee);
        return "redirect:/emps";
    }

    @RequestMapping("delete")
    public String delete(Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }
}
